package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.usian.common.enums.AppHttpCodeEnum;
import com.usian.common.exception.LeadException;
import com.usian.wemedia.entity.WmNewsMaterial;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.IWmNewsMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 自媒体图文引用素材信息表 服务实现类
 * </p>
 *
 * @author usian
 * @since 2022-07-07
 */
@Service
public class WmNewsMaterialServiceImpl extends ServiceImpl<WmNewsMaterialMapper, WmNewsMaterial> implements IWmNewsMaterialService {
    /**
     * 根据newId删除
     * @param newId
     */

    @Override
    public void deleteByNewsId(Integer newId) {
        if (newId==null){
            throw new LeadException(AppHttpCodeEnum.PARAM_INVALID,"参数不正确");
        }
        LambdaQueryWrapper<WmNewsMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WmNewsMaterial::getNewsId,newId);
        boolean b = remove(lambdaQueryWrapper);
        if (!b){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"删除失败");
        }
    }

    /**
     * 保存中间表信息
     * @param wmNewsId 图文id
     * @param materialIds 素材id
     * @param type 引用类型 0是内容引用 1是主图引用
     */
    @Override
    public void saveInfoBatch(Integer wmNewsId, List<Integer> materialIds, int type) {
        //创建集合在集合中添加 是多条数据
        ArrayList<WmNewsMaterial> wmNewsMaterialsList = new ArrayList();
        //遍历传过来的素材id
        for (Integer materialId : materialIds) {
            //新建个中间表
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setMaterialId(materialId);
            wmNewsMaterial.setType(type);
            wmNewsMaterial.setNewsId(wmNewsId);
            wmNewsMaterialsList.add(wmNewsMaterial);
        }
        //执行添加方法
        saveBatch(wmNewsMaterialsList);
    }
}
